// login.js
var app = getApp();
import util from '../../../utils/util.js';

Page({
  /**
   * 页面的初始数据
   */
  data: {
    tel:'',
    username: '',
    password: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.setNavigationBarTitle({
      title: '登录'
    });
  },
  
  // 小程序注册获取用户信息
  // ecapi.auth.social
  getUserInfo: function(cb) {
    app.getUserInfo();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  telInputChanged: function (e) {
    this.setData({
      tel: e.detail.value
    })
  },

  codeInputChanged: function (e) {
    this.setData({
      code: e.detail.value
    })
  },

  getVerifyCode: function (e) {
    if (this.data.tel.length != 11){
      wx.showToast({
        title: '手机号码不能为空',
        icon: 'none',
      })
      return
    }
    var fromid=e.detail.formId;
    this.uploadFormId(fromid)
    wx.request({
      url: app.globalData.SERVER+'sms/sendSmsCode',
      method:'POST',
      data:{
        openid:app.globalData.openId,
        smstype:'1',
        tel:this.data.tel,
      },
      success:(res)=>{

        if (parseInt(res.data.code) == 1){
            wx.showToast({
              title: res.data.msg,
            });
          }else{
            wx.showToast({
              title: res.data.msg,
            })
          }

      },
      fail:(err)=>{


      }
    })
  },

  loginbt: function () {
    var that = this;
    wx.removeStorageSync('userinfo')
  

    wx.getLocation({
      success: function (res) {
        console.log(res)
        wx.setStorage({
          key: 'lon',
          data: res.longitude,

        });
        wx.setStorage({
          key: 'lat',
          data: res.latitude,

        });


        that.setData({
          hasLocation: true,
          location: {

            longitude: res.longitude,
            latitude: res.latitude
          }
        })
      }
    })

    if (app.globalData.openId == '') {
      that.startGetUserInfo();
    } else {
      that.login123();
    }
  },

  getDefaultCar:function(){
    var url = app.globalData.SERVER + 'car/getAllMyCars';
    wx.request({
      url: url,
      method: 'POST',
      data: {
        tel: this.data.tel
      },
      success: (res) => {
        if (parseInt(res.data.code) == 1) {
          const arr = res.data.ret
          for (let i = 0; i < arr.length;i++){
            const car = arr[i]
            if (car.isdefault == '1'){
              util.saveData("defaultcar", car);
            }
          }
        } else {
       
        }
      },
      fail: (err) => {
     
      }
    })
  },

  login123:function(){
    var that = this;
    wx.request({
      url: app.globalData.SERVER + 'register/verifyXcxUser',
      method: 'POST',
      data: {
        openid: app.globalData.openId,
        name: app.userInfoInWX.nickName,
        nickname: app.userInfoInWX.nickName,
        gender: app.userInfoInWX.gender == 1 ? '1' : '0',
        headurl: app.userInfoInWX.avatarUrl,
        lon: app.globalData.lon,
        lan: app.globalData.lan,
        smstype: '1',
        tel: this.data.tel,
        code: this.data.code
      },
      success: (res) => {
        if (parseInt(res.data.code) == 1) {
          util.saveData("userinfo", res.data.ret);
          that.getDefaultCar()
          setTimeout(() => {
                wx.navigateBack({

                })
          }, 1000);
        } else {
          wx.showToast({
            title: res.data.msg,
          })
        }
      },
      fail: (err) => {
        wx.showToast({
          title: '登录失败',
        })
      }
    })
  },

  startGetUserInfo: function () {
    let that = this;
    wx.login({
      success: res => {
        var code = res.code;
        wx.getSetting({
          success: res => {
            console.log(res);
            if (res.authSetting['scope.userInfo']) {
              // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
              wx.getUserInfo({
                success: res1 => {
                  console.info(res1)
                  let res2 = JSON.parse(res1.rawData);
                  that.setData({
                    userInfoInWX: res2,
                    name: res2.nickName,
                    headUrl: res2.avatarUrl
                  });
                  app.userInfoInWX = res2;
                  wx.request({
                    url: app.globalData.SERVER + 'noticeboard/weixinJM',
                    data: {
                      'iv': res1.iv,
                      'encryptedData': res1.encryptedData,
                      'code': code,
                    },
                    header: {
                      'content-type': 'application/json' // 默认值
                    },
                    success: function (res3) {
                      console.log('noticeboard/weixinJM' + JSON.stringify(res3.data))
                      that.setData({
                        openId: res3.data.openId
                      });
                      app.globalData.openId = res3.data.openId;
                      that.login123();
                    }
                  })
                }
              })
            } else {
              wx.authorize({
                scope: 'scope.userInfo',
                success() {
                  // 用户已经同意小程序使用录音功能，后续调用 wx.startRecord 接口不会弹窗询问
                  wx.getUserInfo({
                    success: res1 => {
                      console.info(res1)
                      let res2 = JSON.parse(res1.rawData);
                      that.setData({
                        userInfoInWX: res2,
                        name: res2.nickName,
                        headUrl: res2.avatarUrl
                      });
                      app.userInfoInWX = res2;
                      wx.request({
                        url: app.globalData.SERVER + 'noticeboard/weixinJM',
                        data: {
                          'iv': res1.iv,
                          'encryptedData': res1.encryptedData,
                          'code': code,
                        },
                        header: {
                          'content-type': 'application/json' // 默认值
                        },
                        success: function (res3) {
                          console.log('noticeboard/weixinJM' + JSON.stringify(res3.data))
                          that.setData({
                            openId: res3.data.openId
                          });
                          app.globalData.openId = res3.data.openId;
                          that.login123();
                        }
                      })
                    }
                  })
                },
                fail () {
                  console.log('noticeboard/weixinJM');
                }
              })
            }
          }
        })
      }
    })
  },

  uploadFormId:function(formId){
    if(formId == undefined){
      return
    }
    wx.request({
      url: app.globalData.SERVER + 'basedata/insertFormId',
      method: 'POST',
      data: {
        carerid: this.data.tel,
        formid: formId,
      },
      success: (res) => {

      },
      fail: (err) => {

      }
    })
  },
});